﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.Support;
using support = MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using DAL = MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Core.Documentset;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using System.Data;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.Core.TransactionsResponse;

namespace MS.InformationManagement.Core.AssociatedActions
{
    public abstract class BaseAsociationActions
    {
        #region Properties

        public string AsociationRadicados { get; set; }
        public Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet CurrentExpediente { get; set; }
        public DAL.DocumentCenter.Expediente CurrentExpedienteEntity { get; set; }
        public string TargetLibrary { get; set; }
        public IRadicado RadicadoBussinesObject { get; set; }
        public string ExpedienteSubject { get; set; }
        public Radicado CurrentRadicadoEntity { get; set; }
        public string SubjectExpediente { get; set; }
        public Tomo CurrentTomoEntity { get; set; }

        #endregion

        #region Constructors

        public BaseAsociationActions(string asocitiationRadicados, string targetLibrary, IRadicado radicado,DAL.DocumentCenter.Expediente expediente, Radicado RadicadoEntity, string subjectExpediente )
        {
            AsociationRadicados = asocitiationRadicados;
            TargetLibrary = targetLibrary;
            RadicadoBussinesObject = radicado;
            CurrentExpedienteEntity = expediente;
            CurrentRadicadoEntity = RadicadoEntity;
            SubjectExpediente = subjectExpediente;
        }

        #endregion

        #region Abstract Methods

        public abstract ITransactionResponse Execute();

        #endregion

        #region Private Methods

        protected void AddRadicadoExpediente()
        {
            RadicadoBussinesObject.NewRadicado(CurrentExpediente.Folder);
        }

        protected void CreateExpediente(Office.DocumentSet parentDocument)
        {
            //Getting subserie and subseccion
            string subSerieName = string.Empty;
            //string subSeccionName = string.Empty;
            string dependencia = string.Empty;
            Subserie subserie = new Subserie();
            string serie = string.Empty;

            if(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_TRD] != null)
                subserie = QueryRecordsSiteHelper<Subserie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SUBSERIE, int.Parse(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_TRD].ToString()));

            serie = QueryRecordsSiteHelper<Serie>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SERIE, (int)subserie.Serie.Id).Código;
            //if(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_SUBSECCION] != null)
            //    subSeccionName = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SECCION, int.Parse(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_SUBSECCION].ToString())).Código;

            if (parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET] != null)
                dependencia = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntityById(GlobalConstants.LIST_BIBLIOTECA_SECCION, int.Parse(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET].ToString())).Código;

            CurrentExpedienteEntity = new DAL.DocumentCenter.Expediente();
            CurrentExpedienteEntity.Asunto = SubjectExpediente;
            
            //CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_KIND] = TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_TIPOS, GlobalConstants.METADATA_TERM_TIPO_EXPEDIENTE); ;
            CurrentExpedienteEntity.SubSeccion = parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_SUBSECCION] == null ? 0 : int.Parse(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_SUBSECCION].ToString());
            CurrentExpedienteEntity.Subserie = parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_TRD] == null ? 0 : int.Parse(parentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCSET_TRD].ToString());
            CurrentExpedienteEntity.Código = dependencia + "-" + serie + "-" + subserie.Código;
            CurrentExpedienteEntity.FolioInicial = 1;
            CurrentExpedienteEntity.UbicaciónFisica = "";
            CurrentExpedienteEntity.TipoUbicación = TipoUbicación.CAJA;
            CurrentExpedienteEntity.FechaInicial = (DateTime)parentDocument.Folder.Item[SPBuiltInFieldId.Created];
            CurrentExpedienteEntity.FechaFinal = DateTime.Now;
            CurrentExpedienteEntity.UsuarioAsignado = SPContext.Current.Web.CurrentUser.LoginName;
            CurrentExpediente = new Expediente.ExpedienteManagement(CurrentExpedienteEntity).CreateExpediente(CurrentExpedienteEntity.UsuarioAsignado, AsociationRadicados);

            //// Se adiciona el tomo y se asigna al expediente
            //CurrentTomoEntity = new TomoActions.TomoActions().getVolumeIfExists(CurrentExpediente.Folder.Name);
        }

        protected bool getExpedienteIfExists(string radId)
        {
            List<string> viewFields = new List<string>() { CustomSiteColumns.FIELD_EXPEDIENTE_ID, CustomSiteColumns.FIELD_DOCUMENT_RADICADO };
            List<string> viewListFields = new List<string>() { "Title" };
            string queryFilter = getExistsQuery(radId);
            SPSiteDataQuery siteQuery = QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, viewListFields, queryFilter);
            var foundedItems = SPContext.Current.Web.GetSiteData(siteQuery);
            bool result = foundedItems == null || foundedItems.Rows.Count == 0 ? false  : foundedItems.Rows[0][CustomSiteColumns.FIELD_EXPEDIENTE_ID] == null || string.IsNullOrEmpty(foundedItems.Rows[0][CustomSiteColumns.FIELD_EXPEDIENTE_ID].ToString()) ? false : true;
            if(result)
                CurrentExpediente = GetDocumentSetByRadicado(foundedItems.Rows[0][CustomSiteColumns.FIELD_EXPEDIENTE_ID].ToString(), CustomSiteColumns.FIELD_EXPEDIENTE_ID, GlobalConstants.CTTN_EXPEDIENTE);
            return result;
        }

        protected Office.DocumentSet GetDocumentSetById(int id)
        {
            var spFolder = SPContext.Current.Web.Lists[TargetLibrary].GetItemById(id).Folder;
            return Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
        }

        protected Office.DocumentSet GetDocumentSetById(int id,string listName)
        {
            var spFolder = SPContext.Current.Web.Lists[listName].GetItemById(id).Folder;
            return Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(spFolder);
        }


        protected Office.DocumentSet GetDocumentSetByRadicado(string radicado, string filterField)
        {
            string camlQuery = string.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>",filterField,radicado);
            List<string> viewFields = new List<string>() { "ID" };
            List<string> viewListFields = new List<string>() { "Title" };
            SPSiteDataQuery query = QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, viewListFields, camlQuery);
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            if (foundedItems == null || foundedItems.Rows.Count == 0) return null;
            return GetDocumentSetById(int.Parse(foundedItems.Rows[0]["ID"].ToString()), foundedItems.Rows[0][3].ToString());
        }

        protected Office.DocumentSet GetDocumentSetByRadicado(string radicado, string filterField, string contentType)
        {
            string camlQuery = string.Format("<Where><And><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq><Eq><FieldRef Name='{2}' /><Value Type='Text'>{3}</Value></Eq></And></Where>", filterField, radicado, UserLibraryHelper.ContentTypeFieldName, contentType);
            List<string> viewFields = new List<string>() { "ID", CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID };
            List<string> viewListFields = new List<string>() { "Title" };
            SPSiteDataQuery query = QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, viewListFields, camlQuery);
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            if (foundedItems == null || foundedItems.Rows.Count == 0) return null;
            return GetDocumentSetById(int.Parse(foundedItems.Rows[0]["ID"].ToString()), foundedItems.Rows[0][4].ToString());
        }

        private string getExistsQuery(string idRadicado)
        { 
            List<string> fields = new List<string>(){ CustomSiteColumns.FIELD_DOCUMENT_RADICADO };
            //List<string> fields = new List<string>() { CustomSiteColumns.FIELD_EXPEDIENTE_ID };
            List<string> values = new List<string>(){ idRadicado };
            List<string> types = new List<string>(){ "Text" };
            List<string> operatorTypes = new List<string>(){ "Eq" };
            string _cadena = string.Empty;
            return support.CamlHelper.CreateCAMLQuery(values.ToArray(), fields.ToArray(), types.ToArray(), operatorTypes.ToArray(), ref _cadena); 
        }

        protected void updateNewRadicado(Office.DocumentSet childDocument, bool willBeMoved)
        {
            childDocument.Folder.Item[CustomSiteColumns.FIELD_VOLUME_ID] = childDocument.Folder.Item[CustomSiteColumns.FIELD_VOLUME_ID] == null ? CurrentTomoEntity.Id : childDocument.Folder.Item[CustomSiteColumns.FIELD_VOLUME_ID];
            childDocument.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ID] = CurrentExpediente.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ID];
            childDocument.Folder.Item[CustomSiteColumns.FIELD_CURRENT_ACTION] = willBeMoved ? "MoveTo" : null;
            childDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_FILED] = true;
            childDocument.Folder.Item.Update();
            childDocument.Folder.Update();

        }

        protected void UpdateContentType(SPContentTypeId contentType, Guid listId, int itemId)
        {
            SPFolder currentFolder = SPContext.Current.Web.Lists[listId].GetItemById(itemId).Folder;
            currentFolder.Item[SPBuiltInFieldId.ContentTypeId] = contentType;
            currentFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_FILED] = true;
            currentFolder.Item[CustomSiteColumns.FIELD_VOLUME_ID] = CurrentTomoEntity.Id;
            currentFolder.Item.Update();
            currentFolder.Update();
        }

        #endregion

    }
}
